package org.fastmvc.resource.location;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;

import org.fastmvc.resource.FastMvcResource;
import org.fastmvc.resource.location.impl.ErrorResourceLocation;
import org.fastmvc.resource.location.impl.FileResourceLocation;
import org.fastmvc.resource.location.impl.JarResourceLocation;

/**
 * <类描述>
 *
 * @author tangch
 * @date 2017年11月08日 9:38
 */
public abstract class ResourceLocation {


	public abstract String getId();

	public abstract void scan(String base, Pattern pattern, List<FastMvcResource> list);

	public static ResourceLocation file(File root) {
		try {
			if (!root.exists()) {
				return ErrorResourceLocation.make(root);
			}
			return new FileResourceLocation(root.getAbsoluteFile().getCanonicalFile());
		} catch (Exception e) {
			return ErrorResourceLocation.make(root);
		}
	}

	public static ResourceLocation jar(String jarPath) {
		try {
			return new JarResourceLocation(jarPath);
		} catch (Exception e) {
			return ErrorResourceLocation.make(jarPath);
		}
	}

	public static String getJarPath(String jarPath) {
		if (jarPath.startsWith("zip:")) {
			jarPath = jarPath.substring(4);
		}
		if (jarPath.startsWith("file:/")) {
			jarPath = jarPath.substring("file:/".length());
			if (!new File(jarPath).exists() && !jarPath.startsWith("/")) {
				jarPath = "/" + jarPath;
			}
		}
		try {
			return new File(jarPath).getAbsoluteFile().getCanonicalPath();
		}
		catch (IOException e) {
			return jarPath;
		}
	}


	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (obj instanceof ResourceLocation)
			return ((ResourceLocation)obj).getId().equals(this.getId());
		return false;
	}

	@Override
	public int hashCode() {
		return getId().hashCode();
	}
}
